package com.rong.ruiji.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rong.ruiji.common.BaseContext;
import com.rong.ruiji.dto.DishDto;
import com.rong.ruiji.entity.Category;
import com.rong.ruiji.entity.Dish;
import com.rong.ruiji.entity.DishFlavor;
import com.rong.ruiji.entity.Employee;
import com.rong.ruiji.mapper.DishMapper;
import com.rong.ruiji.mapper.EmployeeMapper;
import com.rong.ruiji.service.DishFlavorService;
import com.rong.ruiji.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;
    /**
     * 新增菜品，同时保存对应的口味数据
     * @param dishDto
     */
    @Transactional
    @Override
    public void saveWithFlavor(Long emp, DishDto dishDto) {
        BaseContext.setCurrentId(emp);
        //保存菜品的基本信息
            this.save(dishDto);
            Long id = dishDto.getId();
        //保存菜品口味表
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(id);
        }
        dishFlavorService.saveBatch(flavors);
    }

    /**
     * 根据id查询菜品以及口味信息
     * @param id
     * @return
     */
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        DishDto dishDto = new DishDto();
        Dish dish = this.getById(id);
        BeanUtils.copyProperties(dish,dishDto);
//        Category category = categoryService.getById(dish.getCategoryId());
//        dishDto.setCategoryName(category.getName());
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(DishFlavor::getDishId,id);
        List<DishFlavor> flavors = dishFlavorService.list(lambdaQueryWrapper);
        dishDto.setFlavors(flavors);
        return dishDto;
    }

    @Override
    @Transactional
    public void updateWithFlavor(Long emp,DishDto dishDto) {
        BaseContext.setCurrentId(emp);

        Long dishId = dishDto.getId();

        //保存菜品的基本信息
        this.updateById(dishDto);

        //获取原来的口味
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(DishFlavor::getDishId,dishId);
        //移除原来的口味
        dishFlavorService.remove(queryWrapper);
        //获取新的口味
        List<DishFlavor> currentFlavors = dishDto.getFlavors();
        for (DishFlavor flavor : currentFlavors) {
            flavor.setDishId(dishId);
        }
        dishFlavorService.saveBatch(currentFlavors);
    }
}
